package com.kedacom.freedomLabel.service;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.kedacom.freedomLabel.AppExecutors;
import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.initdata.InitAll;
import com.kedacom.freedomLabel.initdata.bean.ClonePostUtil;
import com.kedacom.freedomLabel.initdata.bean.EventBusMessage;
import com.kedacom.freedomLabel.initdata.bean.Post;
import com.kedacom.freedomLabel.initdata.bean.PostMessage;
import com.kedacom.freedomLabel.initdata.bean.PostProduct;
import com.kedacom.freedomLabel.initdata.bean.PostRebackMess;
import com.kedacom.freedomLabel.initdata.bean.ProductDetail;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.lego.message.LegoMessageManager;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.seray.scaleviewlib.utils.LogUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class UpdateDateService extends IntentService {


    private static AppExecutors sExecutors;

    private static Gson gson = new GsonBuilder()
            .serializeNulls()
            .create();

    private static Handler sHandler = new Handler();

    public static String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    static {
        sExecutors = AppExecutors.getInstance();
    }


    public UpdateDateService() {
        super("UpdateDateService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {


        if (intent != null) {


            String deviceCodeStr = intent.getStringExtra("deviceId");
            String baseUrl = intent.getStringExtra("baseUrl");


            Date threeDay = getDateBefore(new Date(), 3);
            long startTime = convert2long(DateToString(threeDay) + " " + "00:00:00");
            long endTime = convert2long(DateToString(new Date()) + " " + "23:59:59");

            AppExecutors.getInstance().queryIO()
                    .submit(() -> {
                        List<Post> threeDayPost = AppDatabase.getInstance().getPostDao()
                                .getThreeDayPost(startTime, endTime);

                        if (threeDayPost.size() == 0) {
                            LogUtils.d("threeDayPost=====为空");
                            return;
                        } else {

                            postService(baseUrl, deviceCodeStr, threeDayPost);
                        }

                    });


        }


    }


    private void postService(String baseUrl, String deviceCodeStr, List<Post> postList) {

        PostMessage postMessage = new PostMessage();

        List<PostProduct> postProductList = new ArrayList<>();
        postProductList.clear();

        for (Post post : postList) {
            PostProduct postProduct = new PostProduct();
            ClonePostUtil.ClonePost(post, postProduct);
            postProductList.add(postProduct);
        }

        postMessage.setDeviceCode(deviceCodeStr);
        postMessage.setTime(formatter.format(System.currentTimeMillis()));
        postMessage.setList(postProductList);

        String postStr = gson.toJson(postMessage);
        LogUtils.d("Services==json=====" + postStr);
//        OkGo.<String>get(baseUrl + "reback.json")
        OkGo.<String>post(baseUrl + "/Services/uploadWeightInfo")
                .upJson(postStr)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            PostRebackMess postRebackMess = gson.fromJson(response.body(),
                                    new TypeToken<PostRebackMess>() {
                                    }.getType());
                            if (postRebackMess.getCode() == 200) {

                                sExecutors.queryIO().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {

                                           for (Post postUpdate : postList) {
                                               postUpdate.setPostSuccess(1);
                                                    AppDatabase.getInstance().getPostDao().update(postUpdate);
                                           }
                                            LogUtils.d("success=======成功");

                                        } catch (Exception e) {
                                            LogUtils.d("error"+ e.toString());
                                        }

                                    }
                                });


                            } else {
                                LogUtils.d("error====service 提交异常");
                            }
                        } catch (Exception e) {
                            LogUtils.d("error====service 提交异常");
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.d("error====service 提交异常");
                    }
                });


    }

    public static String DateToString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String str = sdf.format(date);
        return str;
    }

    public static Date getDateBefore(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.getTime();
    }

    public static long convert2long(String date) {
        try {
            if (!TextUtils.isEmpty(date)) {
                SimpleDateFormat sf = new SimpleDateFormat(TIME_FORMAT);
                return sf.parse(date).getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0l;
    }
}
